package com.wl.rjwmc.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wl.rjwmc.DTO.DishDto;
import com.wl.rjwmc.Dao.DishDao;
import com.wl.rjwmc.DoMain.Dish;
import com.wl.rjwmc.DoMain.DishFlavor;
import com.wl.rjwmc.Service.DishFlavorService;
import com.wl.rjwmc.Service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
//        保存原来表的数据
        this.save(dishDto);
//        菜品ID
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(e ->{
//            将ID加上
            e.setDishId(dishId);
            return e;
        }).collect(Collectors.toList());
//        保存菜品口味数据到菜品口味表
        dishFlavorService.saveBatch(flavors);
    }

    @Transactional
    @Override
    public DishDto getByWithFlavor(Long id) {
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        //清理当前菜品对应口味数据---dish_flavor表的delete操作
        dishFlavorService.remove(queryWrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(e ->{
            e.setDishId(dishDto.getId());
            return e;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }
}
